
Imports System.Runtime.InteropServices
#If Not (PocketPC OrElse Smartphone) Then
Imports Microsoft.Win32.SafeHandles
#End If

Public Module winapi
#If Not (PocketPC OrElse Smartphone) Then
    <DllImport("kernel32.dll", EntryPoint:="LoadLibrary", SetLastError:=True)> _
    Public Function loadlibrary(ByVal fileName As String) As IntPtr
    End Function

    <DllImport("kernel32.dll", EntryPoint:="LoadLibraryA", SetLastError:=True)> _
    Public Function loadlibraryA(ByVal fileName As String) As IntPtr
    End Function

    <DllImport("kernel32.dll", EntryPoint:="GetProcAddress", SetLastError:=True)> _
    Public Function getprocAddress(ByVal libHandle As IntPtr, ByVal procName As String) As IntPtr
    End Function

    <DllImport("kernel32.dll", EntryPoint:="FreeLibrary", SetLastError:=True)> _
    Public Function freelibrary(ByVal libHandle As IntPtr) As Boolean
    End Function

    <DllImport("kernel32.dll", EntryPoint:="GetLastError", SetLastError:=True)> _
    Public Function getlastError() As Int32
    End Function

    Public Class unmanagedFileLoader
        Public Const INVALID_HANDLE_VALUE As Short = -1

        Public Const FILE_ATTRIBUTE_ARCHIVE As Int32 = &H20
        Public Const FILE_ATTRIBUTE_NORMAL As Int32 = &H80
        Public Const FILE_ATTRIBUTE_ENCRYPTED As Int32 = &H4000
        Public Const FILE_ATTRIBUTE_HIDDEN As Int32 = &H2
        Public Const FILE_ATTRIBUTE_OFFLINE As Int32 = &H1000
        Public Const FILE_ATTRIBUTE_READONLY As Int32 = &H1
        Public Const FILE_ATTRIBUTE_SYSTEM As Int32 = &H4
        Public Const FILE_ATTRIBUTE_TEMPORARY As Int32 = &H100

        Public Const GENERIC_READ As Int32 = &H80000000
        Public Const GENERIC_WRITE As Int32 = &H40000000

        Public Const FILE_SHARE_NONE As Int32 = &H0
        Public Const FILE_SHARE_DELETE As Int32 = &H4
        Public Const FILE_SHARE_READ As Int32 = &H1
        Public Const FILE_SHARE_WRITE As Int32 = &H2

        Public Const CREATE_NEW As Int32 = &H1
        Public Const CREATE_ALWAYS As Int32 = &H2
        Public Const OPEN_EXISTING As Int32 = &H3
        Public Const OPEN_ALWAYS As Int32 = &H4
        Public Const TRUNCATE_EXISTING As Int32 = &H5

        <DllImport("kernel32.dll", SetLastError:=True)> _
        Public Shared Function CreateFile(ByVal lpFileName As String, ByVal dwDesiredAccess As Int32, _
                                            ByVal dwShareMode As Int32, ByVal lpSecurityAttributes As IntPtr, _
                                            ByVal dwCreationDisposition As Int32, _
                                            ByVal dwFlagsAndAttributes As Int32, _
                                            ByVal hTemplateFile As IntPtr) As SafeFileHandle
        End Function

        Protected Friend handle As SafeFileHandle = Nothing

        Public Sub New(ByVal Path As String, ByVal readwrite As Int32, ByVal createmode As Int32)
            load(Path, readwrite, createmode)
        End Sub

        Public Sub New()
        End Sub

        Public Function load(ByVal Path As String, ByVal readwrite As Int32, ByVal createmode As Int32) As SafeFileHandle
            If Not isemptystring(Path) Then
                handle = CreateFile(Path, readwrite, 0, IntPtr.Zero, createmode, 0, IntPtr.Zero)
                If handle.IsInvalid Then
                    reset()
                End If
            End If

            Return handle
        End Function

        Public Function filehandle() As SafeFileHandle
            Return handle
        End Function

        Public Sub reset()
            If Not handle Is Nothing Then
                handle.Dispose()
                handle = Nothing
            End If
            GC.KeepAlive(handle)
        End Sub

        Protected Overrides Sub Finalize()
            reset()
            MyBase.Finalize()
        End Sub
    End Class

    <DllImport("kernel32.dll")> _
    Public Function CreateToolhelp32Snapshot(ByVal flags As UInt32, ByVal processid As UInt32) As IntPtr
    End Function

    <DllImport("kernel32.dll")> _
    Public Function CloseToolhelp32Snapshot(ByVal handle As IntPtr) As Int32
    End Function

    <DllImport("kernel32.dll")> _
    Public Function Process32First(ByVal handle As IntPtr, ByRef pe As PROCESSENTRY32) As Int32
    End Function

    <DllImport("kernel32.dll")> _
    Public Function Process32Next(ByVal handle As IntPtr, ByRef pe As PROCESSENTRY32) As Int32
    End Function

    <DllImport("kernel32.dll")> _
    Public Function Thread32First(ByVal handle As IntPtr, ByRef te As THREADENTRY32) As Boolean
    End Function

    <DllImport("kernel32.dll")> _
    Public Function Thread32Next(ByVal handle As IntPtr, ByRef te As THREADENTRY32) As Boolean
    End Function

    <DllImport("kernel32.dll")> _
    Private Function OpenProcess(ByVal flags As Int32, ByVal fInherit As Boolean, ByVal PID As Int32) As IntPtr
    End Function

    <DllImport("kernel32.dll")> _
    Public Function TerminateProcess(ByVal hProcess As IntPtr, ByVal ExitCode As UInt32) As Boolean
    End Function

    <DllImport("kernel32.dll")> _
    Public Function CloseHandle(ByVal handle As IntPtr) As Boolean
    End Function

    <DllImport("kernel32.dll")> _
    Public Function SetThreadPriority(ByVal handle As IntPtr, ByVal nPriority As Int32) As Boolean
    End Function

    <DllImport("kernel32.dll")> _
    Public Function GetThreadPriority(ByVal handle As IntPtr) As Int32
    End Function

    <DllImport("kernel32.dll")> _
    Public Function OpenThread(ByVal dwDesiredAccess As Int32 _
                                , ByVal bInheritHandle As Boolean _
                                , ByVal dwThreadId As Int32) As IntPtr
    End Function

    Public Delegate Function ConsoleCtrlDelegate(ByVal dwCtrlType As Int32) As Boolean

    <DllImport("kernel32.dll")> _
    Public Function SetConsoleCtrlHandler(ByVal HandlerRoutine As ConsoleCtrlDelegate, ByVal Add As Boolean) As Boolean
    End Function

    <DllImport("kernel32.dll")> _
    Public Function GetShortPathName(ByVal lpszLongPath As String _
                                    , ByVal lpszShortPath As Text.StringBuilder _
                                    , ByVal cchBuffer As Int32) As Int32
    End Function

    Public Class windowsMessage
        Public Const WM_CLOSE As Int64 = &H10
    End Class

    <DllImport("user32.dll", CharSet:=CharSet.Auto)> _
    Public Function SendMessage(ByVal hWnd As Int32, ByVal msg As Int32, _
                                ByVal wParam As Int32, ByVal lparam As Int32) As Int32
    End Function

    <DllImport("winmm.dll")> _
    Public Sub timeBeginPeriod(ByVal period As UInt32)
    End Sub

    <DllImport("winmm.dll")> _
    Public Sub timeEndPeriod(ByVal period As UInt32)
    End Sub

    <DllImport("kernel32.dll")> _
    Public Function SwitchToThread() As Boolean
    End Function

    <DllImport("kernel32.dll")> _
    Public Function QueryPerformanceCounter(ByRef x As Int64) As Int16
    End Function

    <DllImport("kernel32.dll")> _
    Public Function QueryPerformanceFrequency(ByRef x As Int64) As Int16
    End Function


#Else 'if PocketPC OrElse Smartphone then

    <DllImport("toolhelp.dll")> _
    Public Function CreateToolhelp32Snapshot(ByVal flags As UInt32, ByVal processid As UInt32) As IntPtr
    End Function

    <DllImport("toolhelp.dll")> _
    Public Function CloseToolhelp32Snapshot(ByVal handle As IntPtr) As Int32
    End Function

    <DllImport("toolhelp.dll")> _
    Public Function Process32First(ByVal handle As IntPtr, ByRef pe As PROCESSENTRY32) As Boolean
    End Function

    <DllImport("toolhelp.dll")> _
    Public Function Process32Next(ByVal handle As IntPtr, ByRef pe As PROCESSENTRY32) As Boolean
    End Function

    <DllImport("toolhelp.dll")> _
    Public Function Thread32First(ByVal handle As IntPtr, ByRef te As THREADENTRY32) As Boolean
    End Function

    <DllImport("toolhelp.dll")> _
    Public Function Thread32Next(ByVal handle As IntPtr, ByRef te As THREADENTRY32) As Boolean
    End Function

    <DllImport("coredll.dll")> _
    Public Function OpenProcess(ByVal flags As Int32, ByVal fInherit As Boolean, ByVal PID As Int32) As IntPtr
    End Function

    <DllImport("coredll.dll")> _
    Public Function TerminateProcess(ByVal hProcess As IntPtr, ByVal ExitCode As UInt32) As Boolean
    End Function

    <DllImport("coredll.dll")> _
    Public Function CloseHandle(ByVal handle As IntPtr) As Boolean
    End Function

    <DllImport("coredll.dll")> _
    Public Function SetThreadPriority(ByVal handle As IntPtr, ByVal nPriority As Int32) As Boolean
    End Function

    <DllImport("coredll.dll")> _
    Public Function GetThreadPriority(ByVal handle As IntPtr) As Int32
    End Function

    <DllImport("coredll.dll")> _
    Public Function CeSetThreadPriority(ByVal handle As IntPtr, ByVal nPriority As Int32) As Boolean
    End Function

    <DllImport("coredll.dll")> _
    Public Function CeGetThreadPriority(ByVal handle As IntPtr) As Int32
    End Function

    <DllImport("coredll.dll")> _
    Public Function OpenThread(ByVal dwDesiredAccess As Int32 _
                                , ByVal bInheritHandle As Boolean _
                                , ByVal dwThreadId As Int32) As IntPtr
    End Function

    Public Function SetThreadPriorityEx(ByVal threadID As UInt32, ByVal priority As Int32) As Boolean
        Dim handle As IntPtr = Nothing
        handle = OpenThread(ThreadAccessRight.THREAD_SET_INFORMATION, False, threadID)
        Return CeSetThreadPriority(handle, priority)
    End Function

#End If

    Public Const INVALID_HANDLE_VALUE As Int32 = -1

    Public Const TH32CS_SNAPHEAPLIST As Int32 = &H1
    Public Const TH32CS_SNAPPROCESS As Int32 = &H2
    Public Const TH32CS_SNAPTHREAD As Int32 = &H4
    Public Const TH32CS_SNAPMODULE As Int32 = &H8
    Public Const TH32CS_SNAPALL As Int32 = TH32CS_SNAPPROCESS Or TH32CS_SNAPHEAPLIST _
                                            Or TH32CS_SNAPTHREAD Or TH32CS_SNAPMODULE

    Public Const PROCESS_TERMINATE As Int32 = 1
    Public Const PROCESS_QUERY_INFORMATION As Int32 = 1024
    Public Const PROCESS_VM_READ As Int32 = 16
    Public Const PROCESS_ALL_ACCESS As Int32 = &H1F0FFF

    Public Const MAX_PATH As Int32 = 260

    Public Const CTRL_C_EVENT As Int32 = 0
    Public Const CTRL_BREAK_EVENT As Int32 = 1
    Public Const CTRL_CLOSE_EVENT As Int32 = 2
    '3 is reserved
    '4 is reserved
    Public Const CTRL_LOGOFF_EVENT As Int32 = 5
    Public Const CTRL_SHUTDOWN_EVENT As Int32 = 6

    <StructLayout(LayoutKind.Sequential)> _
    Public Class PROCESSENTRY32
        Private Const SizeOffset As Integer = 0
        Private Const UsageOffset As Integer = 4
        Private Const ProcessIDOffset As Integer = 8
        Private Const DefaultHeapIDOffset As Integer = 12
        Private Const ModuleIDOffset As Integer = 16
        Private Const ThreadsOffset As Integer = 20
        Private Const ParentProcessIDOffset As Integer = 24
        Private Const PriClassBaseOffset As Integer = 28
        Private Const dwFlagsOffset As Integer = 32
        Private Const ExeFileOffset As Integer = 36
        Private Const MemoryBaseOffset As Integer = 556
        Private Const AccessKeyOffset As Integer = 560
        Private Const Size As Integer = 564
        Private Const MAX_PATH As Integer = 260

        Public dwSize As UInt32
        Public cntUsage As UInt32
        Public th32ProcessID As UInt32
        Public th32DefaultHeapID As UInt32
        Public th32ModuleID As UInt32
        Public cntThreads As UInt32
        Public th32ParentProcessID As UInt32
        Public pcPriClassBase As Long
        Public dwFlags As UInt32
        Protected Friend _szExeFile As String
        Public th32MemoryBase As UInt32
        Public th32AccessKey As UInt32

        Public Sub New()
        End Sub

        Public Sub New(ByRef aData As Byte())
            dwSize = GetUInt(aData, SizeOffset)
            cntUsage = GetUInt(aData, UsageOffset)
            th32ProcessID = GetUInt(aData, ProcessIDOffset)
            th32DefaultHeapID = GetUInt(aData, DefaultHeapIDOffset)
            th32ModuleID = GetUInt(aData, ModuleIDOffset)
            cntThreads = GetUInt(aData, ThreadsOffset)
            th32ParentProcessID = GetUInt(aData, ParentProcessIDOffset)
            pcPriClassBase = CLng(GetUInt(aData, PriClassBaseOffset))
            dwFlags = GetUInt(aData, dwFlagsOffset)
            _szExeFile = GetString(aData, ExeFileOffset, MAX_PATH)
            th32MemoryBase = GetUInt(aData, MemoryBaseOffset)
            th32AccessKey = GetUInt(aData, AccessKeyOffset)
        End Sub

        Public Shared Function GetUInt(ByVal aData As Byte(), ByVal Offset As Integer) As UInteger
            Return BitConverter.ToUInt32(aData, Offset)
        End Function

        Public Shared Sub SetUInt(ByVal aData As Byte(), ByVal Offset As Integer, ByVal Value As Integer)
            Dim buint As Byte() = BitConverter.GetBytes(Value)
            Buffer.BlockCopy(buint, 0, aData, Offset, buint.Length)
        End Sub

        Public Shared Function GetUShort(ByVal aData As Byte(), ByVal Offset As Integer) As UShort
            Return BitConverter.ToUInt16(aData, Offset)
        End Function

        Public Shared Sub SetUShort(ByVal aData As Byte(), ByVal Offset As Integer, ByVal Value As Integer)
            Dim bushort As Byte() = BitConverter.GetBytes(CShort(Value))
            Buffer.BlockCopy(bushort, 0, aData, Offset, bushort.Length)
        End Sub

        Public Shared Function GetString(ByVal aData As Byte(), ByVal Offset As Integer, ByVal Length As Integer) _
                                                                                                            As String
            Dim sReturn As String = encoding.unicode.GetString(aData, Offset, Length)
            Return sReturn
        End Function

        Public Shared Sub SetString(ByVal aData As Byte(), ByVal Offset As Integer, ByVal Value As String)
            Dim arr As Byte() = encoding.ascii.GetBytes(Value)
            Buffer.BlockCopy(arr, 0, aData, Offset, arr.Length)
        End Sub

        Public Function szExeFile() As String
            Return _szExeFile.Substring(0, _szExeFile.IndexOf(character.null))
        End Function

    End Class

    <StructLayout(LayoutKind.Sequential)> _
    Public Class THREADENTRY32
        Public dwSize As UInt32
        Public cntUsage As UInt32
        Public th32ThreadID As UInt32
        Public th32OwnerProcessID As UInt32
        Public tpBasePri As Int32
        Public tpDeltaPri As Int32
        Public dwFlags As UInt32
    End Class

    Public Class GenericAccessRight
        Public Const GENERIC_READ As Long = &H80000000
        Public Const GENERIC_WRITE As Long = &H40000000
        Public Const GENERIC_EXECUTE As Long = &H20000000
        Public Const GENERIC_ALL As Long = &H10000000
    End Class

    Public Class StandardAccessRight
        Public Const DELETE As Int32 = &H10000
        Public Const READ_CONTROL As Int32 = &H20000L
        Public Const SYNCHRONIZE As Int32 = &H100000L
        Public Const WRITE_DAC As Int32 = &H40000L
        Public Const WRITE_OWNER As Int32 = &H80000L

        Public Const STANDARD_RIGHTS_ALL As Int32 = DELETE Or READ_CONTROL Or WRITE_DAC Or WRITE_OWNER Or SYNCHRONIZE
        Public Const STANDARD_RIGHTS_EXECUTE As Int32 = READ_CONTROL
        Public Const STANDARD_RIGHTS_READ As Int32 = READ_CONTROL
        Public Const STANDARD_RIGHTS_REQUIRED As Int32 = DELETE Or READ_CONTROL Or WRITE_DAC Or WRITE_OWNER
        Public Const STANDARD_RIGHTS_WRITE As Int32 = READ_CONTROL
    End Class

    Public Class ThreadAccessRight
        Public Const DELETE As Int32 = StandardAccessRight.DELETE
        Public Const READ_CONTROL As Int32 = StandardAccessRight.READ_CONTROL
        Public Const SYNCHRONIZE As Int32 = StandardAccessRight.SYNCHRONIZE
        Public Const WRITE_DAC As Int32 = StandardAccessRight.WRITE_DAC
        Public Const WRITE_OWNER As Int32 = StandardAccessRight.WRITE_OWNER

        Public Const STANDARD_RIGHTS_ALL As Int32 = DELETE Or READ_CONTROL Or WRITE_DAC Or WRITE_OWNER Or SYNCHRONIZE
        Public Const STANDARD_RIGHTS_EXECUTE As Int32 = READ_CONTROL
        Public Const STANDARD_RIGHTS_READ As Int32 = READ_CONTROL
        Public Const STANDARD_RIGHTS_REQUIRED As Int32 = DELETE Or READ_CONTROL Or WRITE_DAC Or WRITE_OWNER
        Public Const STANDARD_RIGHTS_WRITE As Int32 = READ_CONTROL

        Public Const THREAD_ALL_ACCESS As Int32 = (STANDARD_RIGHTS_REQUIRED Or SYNCHRONIZE Or &H3FF)
        Public Const THREAD_DIRECT_IMPERSONATION As Int32 = &H200
        Public Const THREAD_GET_CONTEXT As Int32 = &H8
        Public Const THREAD_IMPERSONATE As Int32 = &H100
        Public Const THREAD_QUERY_INFORMATION As Int32 = &H40
        Public Const THREAD_QUERY_LIMITED_INFORMATION As Int32 = &H800
        Public Const THREAD_SET_CONTEXT As Int32 = &H10
        Public Const THREAD_SET_INFORMATION As Int32 = &H20
        Public Const THREAD_SET_LIMITED_INFORMATION As Int32 = &H400
        Public Const THREAD_SET_THREAD_TOKEN As Int32 = &H80
        Public Const THREAD_SUSPEND_RESUME As Int32 = &H2
        Public Const THREAD_TERMINATE As Int32 = &H1
    End Class

    <DllImport("Netapi32.dll")> _
    Public Function NetUserAdd(<MarshalAs(UnmanagedType.LPWStr)> ByVal name As String, ByVal level As Int32 _
                               , ByRef buff As IntPtr, ByVal parm_err As Int32) As Int32
    End Function

    <DllImport("Netapi32.dll")> _
    Public Function NetUserChangePassword(<MarshalAs(UnmanagedType.LPWStr)> ByVal name As String _
                                          , <MarshalAs(UnmanagedType.LPWStr)> ByVal username As String _
                                          , <MarshalAs(UnmanagedType.LPWStr)> ByVal oldpwd As String _
                                          , <MarshalAs(UnmanagedType.LPWStr)> ByVal newpwd As String) As Int32
    End Function

    <DllImport("Netapi32.dll")> _
    Public Function NetUserDel(<MarshalAs(UnmanagedType.LPWStr)> ByVal name As String _
                               , <MarshalAs(UnmanagedType.LPWStr)> ByVal username As String) As Int32
    End Function

    <DllImport("Netapi32.dll")> _
    Public Function NetUserEnum(<MarshalAs(UnmanagedType.LPWStr)> ByVal name As String, ByVal level As Int32 _
                                , ByVal filter As Int32, ByRef bufPtr As IntPtr, ByVal prefmaxlen As Int32 _
                                , ByRef entriesread As Int32, ByRef totalentries As Int32 _
                                , ByRef resume_Handle As Int32) As Int32
    End Function

    <DllImport("Netapi32.dll")> _
    Public Function NetUserGetInfo(<MarshalAs(UnmanagedType.LPWStr)> ByVal name As String _
                                   , <MarshalAs(UnmanagedType.LPWStr)> ByVal username As String _
                                   , ByVal level As Int32, ByRef intptr As IntPtr) As Int32
    End Function

    <DllImport("Netapi32.dll")> _
    Public Function NetUserGetLocalGroups(<MarshalAs(UnmanagedType.LPWStr)> ByVal name As String _
                                              , <MarshalAs(UnmanagedType.LPWStr)> ByVal username As String _
                                              , ByVal level As Int32, ByVal flags As Int32, ByRef intptr As IntPtr _
                                              , ByVal prefmaxlen As Int32, ByRef entriesread As Int32 _
                                              , ByRef totalentries As Int32) As Int32
    End Function

    <DllImport("Netapi32.dll")> _
    Public Function NetUserSetInfo(<MarshalAs(UnmanagedType.LPWStr)> ByVal name As String _
                                        , <MarshalAs(UnmanagedType.LPWStr)> ByVal username As String _
                                        , ByVal level As Int32, ByRef bufptr As IntPtr _
                                        , ByVal parm_err As Int32) As Int32
    End Function

    <DllImport("Netapi32.dll")> _
    Public Function NetApiBufferFree(ByVal buffer As IntPtr) As Int32
    End Function

    <StructLayout(LayoutKind.Sequential, CharSet:=CharSet.Unicode)> _
    Public Structure LOCALGROUP_USERS_INFO
        Public GroupName As String
    End Structure

    Public Interface USER_INFO
    End Interface

    <StructLayout(LayoutKind.Sequential, CharSet:=CharSet.Unicode)> _
    Public Structure USER_INFO_1
        Implements USER_INFO
        <MarshalAs(UnmanagedType.LPWStr)> Public name As String
        <MarshalAs(UnmanagedType.LPWStr)> Public pwd As String
        Public pwdage As Int32
        Public priv As Int32
        <MarshalAs(UnmanagedType.LPWStr)> Public homedir As String
        <MarshalAs(UnmanagedType.LPWStr)> Public comment As String
        Public flags As Int32
        <MarshalAs(UnmanagedType.LPWStr)> Public scriptPath As String
    End Structure

    <StructLayout(LayoutKind.Sequential)> _
    Public Class MIB_TCPROW
        Public dwState As UInt32
        Public dwLocalAddr As UInt32
        Public dwLocalPort As UInt32
        Public dwRemoteAddr As UInt32
        Public dwRemotePort As UInt32

        Public Sub New()
            dwState = 0
            dwLocalAddr = 0
            dwLocalPort = 0
            dwRemoteAddr = 0
            dwRemotePort = 0
        End Sub
    End Class

    <StructLayout(LayoutKind.Sequential)> _
    Public Class MIB_TCPTABLE
        Public dwNumEntries As UInt32
        Public table() As MIB_TCPROW

        Public Sub New()
            dwNumEntries = 0
            table = Nothing
        End Sub
    End Class

    <DllImport("Iphlpapi.dll")> _
    Public Function GetTcpTable(ByVal pTcpTable As IntPtr, ByRef pdwSize As Int32, ByVal bOrder As Boolean) As Int32
    End Function

    <DllImport("Iphlpapi.dll")> _
    Public Function SendARP(ByVal DestIP As Int32, ByVal SrcIP As Int32, ByRef MacAddr As Int64, _
                            ByRef PhyAddrLen As Int32) As Int32
    End Function

    <DllImport("Ws2_32.dll")> _
    Public Function inet_addr(ByVal ipaddr As String) As Int32
    End Function

    <DllImport("Ws2_32.dll")> _
    Public Function ntohs(ByVal netshort As UInt16) As UInt16
    End Function

    Public Const NO_ERROR As Int32 = 0

End Module
